<template>
  <div class="app-container">
    <!-- <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          @click="handleSearchList()"
          type="primary"
          size="small">
          查询结果
        </el-button>
        <el-button
          style="float: right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="客户名称">
            <el-select
              v-model="listQuery.customId"
              class="input-width"
              placeholder="全部"
              filterable
              clearable
            >
              <el-option
                v-for="item in customList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区域">
            <el-select
              v-model="listQuery.regionId"
              class="input-width"
              placeholder="全部"
              clearable
              @change="getMember"
            >
              <el-option
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务员">
            <el-select
              v-model="listQuery.memberId"
              class="input-width"
              placeholder="全部"
              clearable
            >
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>-->

    <el-card class="filter-container" shadow="never">
      <el-button @click="addTemplate" type="primary" size="small">创建短信模板</el-button>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
    </el-card>

    <el-card class="table-container" shadow="never">
      <el-table ref="productTable" :data="list" style="width: 100%" v-loading="listLoading" border>
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="模板名称" show-overflow-tooltip width="200">
          <template slot-scope="scope">{{ scope.row.templateName }}</template>
        </el-table-column>
        <el-table-column label="模板内容" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.templateContent }}</template>
        </el-table-column>
        <!-- <el-table-column label="短信模板CODE" width="200">
          <template slot-scope="scope">{{ scope.row.templateCode }}</template>
        </el-table-column> -->
        <el-table-column label="场景说明" show-overflow-tooltip width="200">
          <template slot-scope="scope">{{ scope.row.remark }}</template>
        </el-table-column>
        <!-- <el-table-column label="发送状态" width="200">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sendStatus== 0" type="success">全部发送成功</el-tag>
            <el-tag v-else type="danger">部分发送失败</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column label="审核状态" width="200">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.templateStatus== 0" type="warning">审核中</el-tag>
            <el-tag v-if="scope.row.templateStatus== 1" type="success">审核通过</el-tag>
            <el-tag v-if="scope.row.templateStatus== 2" type="danger">审核失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核原因" show-overflow-tooltip width="200">
          <template slot-scope="scope">{{ scope.row.reason }}</template>
        </el-table-column>
        <el-table-column label="创建日期" width="200">
          <template slot-scope="scope">{{ scope.row.createDate }}</template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="300">
          <template slot-scope="scope">
            <el-button @click="openSend(scope.row)" :disabled="scope.row.templateStatus == 0||scope.row.templateStatus == 2" type="text">短信群发</el-button>
            <el-divider direction="vertical"></el-divider>
            <!-- <el-button @click="edit(scope.row)" :disabled="scope.row.sendStatus == 0" type="text">未收到短信用户</el-button>
            <el-divider direction="vertical"></el-divider> -->
            <el-button :disabled="scope.row.templateStatus== 0" @click="edit(scope.row)" type="text">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button :disabled="scope.row.templateStatus== 0" @click="openHistory(scope.row)" type="text">历史记录</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-popconfirm
              @onConfirm="del(scope.row)"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="是否删除本条数据？">
              <el-button  :disabled="scope.row.templateStatus == 0" slot="reference" type="text" :style="{color:scope.row.templateStatus == 0?'#C0C4CC':'#ff0000'}">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[10, 20, 50]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      ></el-pagination>
    </div> -->

    <el-dialog title="拜访记录信息" :visible.sync="visitVisible" width="30%">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="visitVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog width="70%" title="创建短信模板" :visible.sync="addModal">
      <el-form :model="formAdd">
        <el-form-item label="模板名称" :label-width="formLabelWidth">
          <el-input show-word-limit :maxlength="30" v-model="formAdd.templateName" autocomplete="off" placeholder="请输入名称，不超过30字符"></el-input>
        </el-form-item>
        <el-form-item label="模板内容" :label-width="formLabelWidth">
          <el-input show-word-limit type="textarea" :maxlength="500" :rows="4" v-model="formAdd.templateContent" autocomplete="off" placeholder="变量格式：${name}；
示例：尊敬的${name}，您的快递已在飞奔的路上，将在今天${time}送达您的手里，请留意查收。"></el-input>
          <div style="line-height:1.5;padding:20px 0 0">
            <span style="color:red;margin-right:10px">*</span>
            短信字数含"签名+短信内容+变量内容”，短信70个字数含以内，按1条短信计费；超出70个字为长短信，按照67个字数记为1条短信费用。
          </div>
        </el-form-item>
        <el-form-item label="申请说明" :label-width="formLabelWidth">
          <el-input show-word-limit type="textarea" :maxlength="500" :rows="4" v-model="formAdd.remark" autocomplete="off" placeholder="请提供您已上线业务的对应链接（必填）、使用场景说明
对应链接：如官网、应用市场下载页等，内网环境链接可提交测试账号及密码。
使用场景：如场景、事例等详细说明"></el-input>
          <div style="line-height:1.5;padding:20px 0 0">
            请提供您已上线业务的对应链接（必填）、使用场景说明<br/>
            暂时无法支持未上线应用、未备案域名的模板申请
          </div>
        </el-form-item>
        <!-- <el-form-item label="发放时间" :label-width="formLabelWidth">
          <el-radio-group v-model="timeRadio">
            <el-radio :label="1">审核通过立刻推送</el-radio>
            <el-radio :label="2">指定日期推送消息</el-radio>
          </el-radio-group>
          <div v-if="timeRadio == 2">
            <el-date-picker
              v-model="sendTime"
              type="datetime"
              placeholder="请选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addModal = false">取 消</el-button>
        <el-button type="primary" @click="createTemplate">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑短信模板" :visible.sync="editModal">
      <el-form :model="formAdd">
        <el-form-item label="模板名称" :label-width="formLabelWidth">
          <el-input show-word-limit :maxlength="30" v-model="formAdd.templateName" autocomplete="off" placeholder="请输入名称，不超过30字符"></el-input>
        </el-form-item>
        <el-form-item label="模板内容" :label-width="formLabelWidth">
          <el-input show-word-limit type="textarea" :maxlength="500" :rows="4" v-model="formAdd.templateContent" autocomplete="off" placeholder="变量格式：${name}；
示例：尊敬的${name}，您的快递已在飞奔的路上，将在今天${time}送达您的手里，请留意查收。"></el-input>
          <div style="line-height:1.5;padding:20px 0 0">
            <span style="color:red;margin-right:10px">*</span>
            短信字数含"签名+短信内容+变量内容”，短信70个字数含以内，按1条短信计费；超出70个字为长短信，按照67个字数记为1条短信费用。
          </div>
        </el-form-item>
        <el-form-item label="申请说明" :label-width="formLabelWidth">
          <el-input show-word-limit type="textarea" :maxlength="500" :rows="4" v-model="formAdd.remark" autocomplete="off" placeholder="请提供您已上线业务的对应链接（必填）、使用场景说明
对应链接：如官网、应用市场下载页等，内网环境链接可提交测试账号及密码。
使用场景：如场景、事例等详细说明"></el-input>
          <div style="line-height:1.5;padding:20px 0 0">
            请提供您已上线业务的对应链接（必填）、使用场景说明<br/>
            暂时无法支持未上线应用、未备案域名的模板申请
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editModal = false">取 消</el-button>
        <el-button type="primary" @click="editTemplate">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="短信群发" :visible.sync="sendModal">
      <el-form :model="formAdd">
        <el-form-item label="选择人群" :label-width="formLabelWidth">
          <!-- <el-select multiple style="width:100%" v-model="cityCode" placeholder="请选择目标城市">
            <el-option
              v-for="item in cityList"
              :key="item.cityCode"
              :label="`${item.city}(${item.customCount}个)`"
              :value="item.cityCode">
            </el-option>
          </el-select> -->
          <el-radio-group v-model="personRadio">
            <el-radio :label="1">全员发送</el-radio>
            <el-radio :label="2">用户标签</el-radio>
            <el-radio :label="3">证书人群</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="personRadio == 2" label="用户标签" :label-width="formLabelWidth">
          <el-select style="width:100%;" @change="tagChange" v-model="tagId" placeholder="请选择">
            <el-option
              v-for="item in tagList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="personRadio == 3" label="用户标签" :label-width="formLabelWidth">
          <el-radio-group v-model="activeCertClassifyId">
            <el-radio v-for="(item, index) in categoryList" :key="index" :label="item.type">{{item.name}}</el-radio>
          </el-radio-group>
          <el-select style="width:100%;" @change="certChange" v-model="tagId" placeholder="请选择">
            <el-option
              v-for="item in certList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信内容" :label-width="formLabelWidth">
          <div style="border:1px solid #999;padding: 10px;line-height:1.5;" v-html="sendContent?sendContent:'-'">

          </div>
        </el-form-item>
        <el-form-item label="发放时间" :label-width="formLabelWidth">
          <el-radio-group v-model="timeRadio">
            <el-radio :label="1">立刻推送</el-radio>
            <el-radio :label="2">定时发送</el-radio>
          </el-radio-group>
          <div v-if="timeRadio == 2">
            <el-date-picker
              v-model="sendTime"
              type="datetime"
              value-format="yyyy-MM-DD HH:mm:ss"
              placeholder="请选择日期时间">
            </el-date-picker>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendModal = false">取 消</el-button>
        <el-button type="primary" @click="sendMsg">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
      title="历史记录"
      direction="rtl"
      size="1000px"
      :visible.sync="historyModal">
      <div style="padding:0 30px;">
        <el-table ref="multipleTable" v-loading="historyLoading" :data="historyList" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
          <el-table-column label="ID" width="100">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column label="模板名称" width="180">
            <template slot-scope="scope">
              {{ scope.row.templateName }}
            </template>
          </el-table-column>
          <el-table-column label="短信内容" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.templateContent }}
            </template>
          </el-table-column>
          <el-table-column label="发送状态" width="180">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.sendStatus== 0" type="success">全部发送成功</el-tag>
              <el-tag v-else type="danger">部分发送失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发送类型" width="180">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.type== 0" type="primary">即时发送</el-tag>
              <el-tag v-else type="primary">定时发送</el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column label="创建时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.createDate }}
            </template>
          </el-table-column> -->
          <el-table-column label="发送时间" width="180">
            <template slot-scope="scope">
              {{ scope.row.sendTime | formatCreateTime }}
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align:right;margin-top:20px;">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total, sizes,prev, pager, next,jumper"
            :page-size="historyPageObj.pageSize"
            :page-sizes="[10, 20, 50]"
            :current-page.sync="historyPageObj.pageNum"
            :total="historyPageObj.total"
          ></el-pagination>
        </div>

      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getListApi, createTemplateApi, editTemplateApi, deleteTemplateApi, getCityListApi, sendApi, getHistoryApi, sendMessageApi } from "@/api/oprate";
import {
  queryAllTagListApi,
  getCertListApi,
  getCertCategoryListApi
} from '@/api/certseries'
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  memberId: null,
  regionId: null,
  customId: null
};
export default {
  name: "examineSalesmanList",
  data() {
    return {
      tagName: '',
      tagList: [],
      tagId: '',
      dialogVisible: false,
      viewPicUrl: "",
      dialogTableVisible: false,
      ruleForm: {
        description: ""
      },
      formAdd: {
        remark: '',
        templateContent: '',
        templateName: '',
      },
      addModal: false,
      editModal: false,
      formLabelWidth: '80px',
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      areaList: [],
      regionId: null,
      memberList: [],
      statusOptions: [
        {
          label: "全部",
          value: -1
        },
        {
          label: "正常",
          value: 0
        },
        {
          label: "异常",
          value: 1
        }
      ],
      joinVisitLogOptions: [
        {
          label: "已经关联拜访记录",
          value: true
        },
        {
          label: "未关联拜访记录",
          value: false
        }
      ],
      visitObj: {},
      visitVisible: false,
      customList: [],
      templateCode: '',
      eidtId: '',
      templateId: '',
      cityCode: [],
      cityList: [],
      sendModal: false,
      historyPageObj: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      historyModal: false,
      sendContent: '',
      historyLoading: false,
      historyList: [],
      historyId: '',
      personRadio: 1,
      timeRadio: 1,
      sendTime: '',
      activeCertClassifyId: '',
      certList: [],
      categoryList: [],
      activeCertClassifyObj: {}
    }
  },
  created() {
    this.getList();
  },
  watch: {},
  methods: {
    certChange(e) {
      console.log(e)
    },
    fetchData() {
      getCertListApi({
        certseriesTypeCode: this.activeCertClassifyId,
        pageSize: 100,
        pageNum: 1
      }).then((response) => {
        this.certList = response.data.list
      })
    },
    getCertCategoryList() {
      getCertCategoryListApi({
        pageNum: 1,
        pageSize: 100
      }).then((res) => {
        if (res.data.list.length) {
          this.categoryList = res.data.list
          this.activeCertClassifyObj = res.data.list[0]
          this.activeCertClassifyId = res.data.list[0].type
          this.fetchData()
        }
      })
    },
    queryAllTagList() {
      queryAllTagListApi().then((res) => {
        this.tagList = res.data
      })
    },
    tagChange(e) {
      let xx = 0
      this.tagList.forEach((item, index) => {
        if(item.id == e.id) {
          xx = index
        }
      })
      this.tagName = this.tagList[xx].name
    },
    openHistory(row) {
      this.historyModal = true
      this.historyId = row.id
      this.getHistory()
    },
    getHistory() {
      this.historyLoading = true
      getHistoryApi({
        templateId: this.historyId,
        pageNum: this.historyPageObj.pageNum,
        pageSize: this.historyPageObj.pageSize,
      }).then((res) => {
        console.log(res)
        this.historyLoading = false
        this.historyList = res.data.list
        this.historyPageObj.total = res.data.total
      })
    },
    sendMsg() {
      // if(!this.cityCode.length) {
      //   this.$message({
      //     message: '请选择目标城市！',
      //     type: 'error'
      //   })
      //   return false
      // }
      // let arr = []
      // this.cityList.forEach((item) => {
      //   this.cityCode.forEach((itemChild) => {
      //     if(itemChild == item.cityCode) {
      //       arr.push(item.city)
      //     }
      //   })
      // })
      // console.log(this.sendTime)
      sendMessageApi({
        cityCode: '111',
        templateId: this.templateId,
        time: this.timeRadio == 1? '': this.sendTime,
        type: this.timeRadio == 1? 0: 1
      }).then((res) => {
        if(res.code == 200) {
          this.sendModal = false
          this.getList()
        }
      })
    },
    openSend(row) {
      this.queryAllTagList()
      this.getCertCategoryList()
      this.templateId = row.id
      this.sendContent = row.templateContent
      this.sendTime = ''
      this.sendModal = true
      // this.cityCode = []
      // this.getCityList()
    },
    getCityList() {
      getCityListApi({}).then((res) => {
        this.cityList = res.data
      })
    },
    addTemplate() {
      this.formAdd.templateContent = ''
      this.formAdd.templateName = ''
      this.formAdd.remark = ''
      this.addModal = true
    },
    edit(row) {
      this.formAdd.templateContent = row.templateContent
      this.formAdd.templateName = row.templateName
      this.formAdd.remark = row.remark
      this.editId = row.id
      this.templateCode = row.templateCode
      this.editModal = true
    },
    editTemplate() {
      editTemplateApi({
        templateContent: this.formAdd.templateContent,
        templateName: this.formAdd.templateName,
        remark: this.formAdd.remark,
        templateId: this.editId,
        templateCode: this.templateCode
      }).then((res) => {
        if(res.code == 200) {
          this.getList()
          this.editModal = false
        }
      })
    },
    createTemplate() {
      createTemplateApi({
        templateType: 2,
        templateContent: this.formAdd.templateContent,
        templateName: this.formAdd.templateName,
        remark: this.formAdd.remark,
      }).then((res) => {
        if(res.code == 200) {
          this.getList()
          this.addModal = false
        }
      })
    },
    cusChange(e) {
      console.log(e);
    },
    del(row) {
      deleteTemplateApi(row.id).then((res) => {
        this.getList()
      })
    },
    viewPic(url) {
      // console.log(url)
      this.dialogTableVisible = true;
      this.viewPicUrl = url;
    },
    getAllListArea() {
      return getAllListArea({}).then(res => {
        if (res.code == 200) {
          this.areaList = res.data || [];
        }
      });
    },
    getList() {
      this.listLoading = false;
      const data = Object.assign({}, this.listQuery);
      getListApi(data).then(res => {
        this.listLoading = false;
        if (res.code == 200) {
          this.list = res.data
          this.total = res.data.total
        }
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.historyPageObj.pageNum = 1;
      this.historyPageObj.pageSize = val;
      this.getHistory();
    },
    handleCurrentChange(val) {
      this.historyPageObj.pageNum = val;
      this.getHistory();
    },
    handleViewVisit(index, row) {
      this.$router.push({
        path: "/customer/customerDetail",
        query: { id: row.id }
      });
      // visitLogInfo(row.visitLogId).then((res) => {
      //   if (res.code == 200) {
      //     this.visitVisible = true;
      //     this.visitObj = res.data.data
      //   }
      // });
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery);
    }
  }
};
</script>
<style></style>
